package com.ai.task;

import cn.hutool.core.util.StrUtil;
import com.ai.constant.SystemConst;
import com.ai.dao.mapper.BfmUserMapper;
import com.ai.pojo.BfmUser2;
import com.ai.utils.Base64Util;
import com.ai.utils.DESUtil;
import com.ai.utils.DesECBUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description
 * @ClassName SyncTask
 * @Author User
 * @date 2023.06.16
 */


@Component
@EnableScheduling
public class GetLoginPermissions implements SchedulingConfigurer {

    @Autowired
    BfmUserMapper bfmUserMapper;

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.addTriggerTask(() -> process(),
                triggerContext -> {
                    String cron = bfmUserMapper.getCron(1);
                    if (cron.isEmpty()) {
                        System.out.println("cron is null");
                    }
                    return new CronTrigger(cron).nextExecutionTime(triggerContext);
                });
    }

    private void process() {
        BfmUser2 bfmUser2 = new BfmUser2();
        String sysCode = "CQDXAI";
        //调用主账号目标系统登录权限控制接口
        Map<String, String> req = new HashMap<>();
//        req.put("transaction_id", getTransactionId(sysCode));
        req.put("target_sys_code", sysCode);
        req.put("request_time", getRequestTime());
        //获取账号编码
        ArrayList<Map<String, String>> userCodeList = bfmUserMapper.selectUserCode();
        for(Map<String, String> map : userCodeList){
            String main_acct_code = map.get("user_code");
            bfmUser2.setUserCode(main_acct_code);
            //账号问题特殊处理
            if ("huangbo".equals(main_acct_code)) {
                main_acct_code = "huangbo6";
            }
            if ("Mokundong".equals(main_acct_code)) {
                main_acct_code = "mokundong";
            }
            req.put("main_acct_code", main_acct_code);
            String update_status = map.get("update_status");
            String state = map.get("state");
            if ("A".equals(state) && StrUtil.isBlank(update_status)) {
                req.put("transaction_id", getTransactionId(sysCode));
                req.put("action_code", "A");
                JSONObject json = new JSONObject();
                json.putAll(req);
                String singData = json.toString();
                try {
                    String sign = Base64Util.encode(DesECBUtil.encrypt(singData, "49d0a02ce3294de0b23573d7ad4da4bd"));
                    json.put("sign", sign);
                    String jsonData = json.toString();
                    //请求的webservice的url
                    URL url = new URL(SystemConst.URL_TYRZ_PRIV_PROD);
                    //创建http链接
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    //设置请求的方法类型
                    httpURLConnection.setRequestMethod("POST");
                    //设置请求的内容类型
                    httpURLConnection.setRequestProperty("Content-type", "application/json");
                    httpURLConnection.setRequestProperty("X-APP-ID", "4d52df7e60d84ba0497408352947bf11");
                    httpURLConnection.setRequestProperty("X-APP-KEY", "e14cad330219369de5fd1133d7e7b427");
                    httpURLConnection.setRequestProperty("X-CTG-Province-ID", "10544");
                    httpURLConnection.setRequestProperty("X-CTG-VERSION", "V1.0.0");
                    //设置发送数据
                    httpURLConnection.setDoOutput(true);
                    //设置接受数据
                    httpURLConnection.setDoInput(true);
                    //发送数据,使用输出流
                    OutputStream outputStream = httpURLConnection.getOutputStream();
                    //发送数据
                    outputStream.write(jsonData.getBytes());

                    // 显示结果
                    BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        JSONObject rs = JSONObject.parseObject(line);
                        String rsp_code = rs.getString("rsp_code");
                        String rsp_desc = rs.getString("rsp_desc");
                        if("0000".equals(rsp_code)){
                            bfmUser2.setUpdateStatus("10");
                            bfmUser2.setRspDesc(rsp_desc);
                        } else if ("接口无响应".equals(rsp_code)) {
                            bfmUser2.setUpdateStatus("13");
                            bfmUser2.setRspDesc("接口无响应");
                        } else {
                            bfmUser2.setUpdateStatus("12");
                            bfmUser2.setRspDesc(rsp_desc);
                        }
                    }
                    bfmUserMapper.updateState(bfmUser2);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if ("X".equals(state) && "10".equals(update_status)) {
                req.put("transaction_id", getTransactionId(sysCode));
                req.put("action_code", "D");
                JSONObject json = new JSONObject();
                json.putAll(req);
                String singData = json.toString();
                try {
                    String sign = Base64Util.encode(DesECBUtil.encrypt(singData, "49d0a02ce3294de0b23573d7ad4da4bd"));
                    json.put("sign", sign);
                    String jsonData = json.toString();
                    //请求的webservice的url
                    URL url = new URL(SystemConst.URL_TYRZ_PRIV_PROD);
                    //创建http链接
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    //设置请求的方法类型
                    httpURLConnection.setRequestMethod("POST");
                    //设置请求的内容类型
                    httpURLConnection.setRequestProperty("Content-type", "application/json");
                    httpURLConnection.setRequestProperty("X-APP-ID", "4d52df7e60d84ba0497408352947bf11");
                    httpURLConnection.setRequestProperty("X-APP-KEY", "e14cad330219369de5fd1133d7e7b427");
                    httpURLConnection.setRequestProperty("X-CTG-Province-ID", "10544");
                    httpURLConnection.setRequestProperty("X-CTG-VERSION", "V1.0.0");
                    //设置发送数据
                    httpURLConnection.setDoOutput(true);
                    //设置接受数据
                    httpURLConnection.setDoInput(true);
                    //发送数据,使用输出流
                    OutputStream outputStream = httpURLConnection.getOutputStream();
                    //发送数据
                    outputStream.write(jsonData.getBytes());

                    // 显示结果
                    BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        JSONObject rs = JSONObject.parseObject(line);
                        String rsp_code = rs.getString("rsp_code");
                        String rsp_desc = rs.getString("rsp_desc");
                        if("0000".equals(rsp_code)){
                            bfmUser2.setUpdateStatus("20");
                            bfmUser2.setRspDesc(rsp_desc);
                        } else if ("接口无响应".equals(rsp_code)) {
                            bfmUser2.setUpdateStatus("23");
                            bfmUser2.setRspDesc("接口无响应");
                        } else {
                            bfmUser2.setUpdateStatus("22");
                            bfmUser2.setRspDesc(rsp_desc);
                        }
                    }
                    bfmUserMapper.updateState(bfmUser2);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
//            bfmUserMapper.updateState(bfmUser2);
        }
    }

    public String getTransactionId(String sysCode) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        Random rand = new Random();
        String result = "";
        for (int i = 0; i < 10; i++) {
            result += rand.nextInt(6);
        }
        return sysCode + sdf.format(new Date()) + result;
    }

    public String getRequestTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(new Date());
    }
}
